package com.minyue.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.minyue.io.Resources;
import com.minyue.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author ：minyue
 * @date ：Created in 2021/7/22 10:56 下午
 * @description：
 */
public class XMLConfigurationBuilder {

    private Configuration configuration;

    public XMLConfigurationBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parseConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> propertyElements = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        propertyElements.forEach(propertyElement -> {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        });

        //连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //填充configuration
        configuration.setDataSource(comboPooledDataSource);
        //获取mapper部分配置
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        mapperElements.forEach(mapperElement -> {
            String resource = mapperElement.attributeValue("resource");
            InputStream resourcesAsStream = Resources.getResourcesAsStream(resource);
            try {
                xmlMapperBuilder.parse(resourcesAsStream);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        });
        return configuration;
    }
}
